<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Controller;

use Admin\Entity\SelfLocation;
use Admin\Form\SelfLocationForm;
use Admin\Service\SelfLocationManager;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;

/**
 * 自提点
 * Class SelfLocationController
 * @package Admin\Controller
 */
class SelfLocationController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $selfLocationManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager,
        SelfLocationManager $selfLocationManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
        $this->selfLocationManager = $selfLocationManager;
    }

    public function indexAction()
    {
        $selfLocationList = $this->entityManager->getRepository(SelfLocation::class)->findBy([], ['locationSort' => 'ASC', 'locationId' => 'DESC']);

        return ['locationList' => $selfLocationList];
    }

    /**
     * 自提点添加
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $form = new SelfLocationForm();

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $this->selfLocationManager->addSelfLocation($data);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('自提点 %s 添加成功!'), $data['locationName']), $this->translator->translate('自提点设置'));

                return $this->redirect()->toRoute('self-location');
            }
        }

        return ['form' => $form, 'region' => $this->adminCommon()->getRegionSub()];
    }

    /**
     * 自提点编辑
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $locationId     = (int) $this->params()->fromRoute('id', 0);
        $locationInfo   = $this->entityManager->getRepository(SelfLocation::class)->findOneBy(['locationId' => $locationId]);
        if($locationInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该自提点不存在!'));
            return $this->redirect()->toRoute('self-location');
        }

        $form = new SelfLocationForm();

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $this->selfLocationManager->editSelfLocation($data, $locationInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('自提点 %s 编辑成功!'), $data['locationName']), $this->translator->translate('自提点设置'));

                return $this->redirect()->toRoute('self-location');
            }
        } else $form->setData($locationInfo->valuesArray());

        return ['locationInfo' => $locationInfo, 'form' => $form, 'region' => $this->adminCommon()->getRegionSub()];
    }

    /**
     * 删除自提点
     * @return \Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $locationId = (int) $this->params()->fromRoute('id', 0);
        $locationInfo   = $this->entityManager->getRepository(SelfLocation::class)->findOneBy(['locationId' => $locationId]);
        if($locationInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该自提点不存在!'));
            return $this->redirect()->toRoute('self-location');
        }

        $this->selfLocationManager->deleteSelfLocation($locationInfo);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('自提点 %s 删除成功!'), $locationInfo->getLocationName()), $this->translator->translate('自提点设置'));

        return $this->adminCommon()->toReferer();
    }

    /**
     * 获取地理编码（暂未使用）
     * @return JsonModel
     */
    public function ajaxLocationGeoCodingAction()
    {
        $locationAddress = urlencode($this->params()->fromQuery('locationAddress'));
        $locationData = file_get_contents('https://api.map.baidu.com/geocoding/v3/?address='.$locationAddress.'&output=json&ak=&ret_coordtype=gcj02ll');
        return $this->getResponse()->setContent($locationData);
    }
}